﻿using Newtonsoft.Json;
using System.Net.WebSockets;
using System.Text;

namespace xk.mqm.test.userservice
{
    public class WebSocketMiddleware
    {
        private readonly RequestDelegate _next;
        public static Dictionary<string, WebSocket> _userConnections = new Dictionary<string, WebSocket>();

        public WebSocketMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next(context);
                return;
            }
            WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
            string UserId = context.Request.Query["UserId"].ToString();
            // 将用户ID和WebSocket连接添加到映射中
            _userConnections[UserId] = webSocket;
            try
            {
                // 处理WebSocket消息
                await HandleWebSocketMessages(UserId, webSocket);
            }
            catch (Exception e)
            {
                //写入日志
                var bb = e.Message;
            }
            //移除WebSockets集合
            if (_userConnections.ContainsKey(UserId))
            {
                _userConnections.Remove(UserId);
            }
        }
        private async Task HandleWebSocketMessages(string SenderId, WebSocket webSocket)
        {
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result;

            while (webSocket.State == WebSocketState.Open)
            {
                result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.CloseStatus.HasValue)
                {
                    // 关闭WebSocket连接
                    await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
                    return;
                }
                // 解析接收到的消息，获取发送者和接收者ID
                // 假设消息格式是一个JSON对象，包含"from", "to", 和 "content"字段
                var message = Encoding.UTF8.GetString(buffer, 0, result.Count);
                var messageObj = JsonConvert.DeserializeObject<SocketMessage>(message);
                if (messageObj == null) return;
                //发送者标识，由后端这里进行补充或替换
                messageObj.SenderId = SenderId;
                // 如果是广播消息（to字段为空或特定值），则发送给所有用户
                if (string.IsNullOrEmpty(messageObj.TargetId) || messageObj.TargetId == "0")
                {
                    foreach (var connection in _userConnections.Values)
                    {
                        if (connection != webSocket) // 不要将消息发送回发送者
                        {
                            await connection.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                        }
                    }
                }
                else
                {
                    // 如果是点对点消息，则根据接收者ID路由到正确的连接
                    if (_userConnections.TryGetValue(messageObj.TargetId, out WebSocket targetWebSocket))
                    {
                        await targetWebSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None);
                    }
                }
            }
        }
    }
}
